package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public Result findByRids(Integer[] roleIds) {
        try {
            //不可重复
            Set<Integer> integers = new HashSet<>();
            for (Integer roleId : roleIds) {
                List<Permission> permissionList = permissionDao.findByRids(roleId);
                for (Permission permission : permissionList) {
                    Integer id = permission.getId();
                    integers.add(id);
                }
            }
            return new Result(true,"获取权限信息成功",integers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"获取权限信息失败");
        }
    }

    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Permission> page = permissionDao.selectByCondition(queryPageBean.getQueryString());
        PageResult pageResult = new PageResult(page.getTotal(), page);
        return pageResult;
    }

    @Override
    public void deleteById(Integer id) {
        long permissionCount = permissionDao.findCountByPermissionId(id);
        if(permissionCount==0){
            permissionDao.deleteById(id);
        }else {
            throw new RuntimeException("当前权限被引用，不能删除");
        }
    }

    @Override
    public Permission findById(Integer id) {
        Permission permission = permissionDao.findById(id);
        return permission;
    }

    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }
}
